package cn.wolfcode.web.controller;


import cn.wolfcode.domain.ActivityItem;
import cn.wolfcode.domain.Choice;
import cn.wolfcode.mapper.ActivityItemMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IActivityItemService;
import cn.wolfcode.service.IActivityService;
import cn.wolfcode.service.IChoiceService;
import cn.wolfcode.util.RequiredPermission;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/choice")
public class ChoiceController {

    @Autowired
    private IChoiceService choiceService;
    @Autowired
    private IActivityService activityService;
    @Autowired
    private ActivityItemMapper activityItemMapper;
    @Autowired
    private IActivityItemService activityItemService;


    @RequiredPermission(name = "结果页面", expression = "choice:list")
    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") QueryObject qo) {
        PageInfo<Choice> pageInfo = choiceService.query(qo);
        model.addAttribute("pageInfo", pageInfo);
        return "choice/list";
    }


    @RequiredPermission(name = "结果删除", expression = "choice:delete")
    @RequestMapping("/delete")
    public String delete(Long id) {
        if (id != null) {
            choiceService.delete(id);
        }
        return "redirect:/choice/list";
    }


    @RequiredPermission(name = "结果新增/编辑", expression = "choice:saveOrUpdate")
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Choice choice) {
        if (choice.getId() == null) {
            choiceService.save(choice);
        } else {
            choiceService.update(choice);
        }
        return "redirect:/choice/list";
    }


    @RequiredPermission(name = "结果新增/编辑", expression = "choice:saveOrUpdate")
    @RequestMapping("/input")
    public String input(Long id, Model model) {
        if (id != null) {
            model.addAttribute("choice", choiceService.get(id));
        }
        return "choice/input";
    }


    @RequestMapping("/save")
    public String save(Choice choice, Model model, Long id, Long activityId) {
        if (activityService.isSelect(activityId)!=null){
            choiceService.save(choice);
            Long activityItemId = choice.getActivityItemId();
            ActivityItem activityItem = activityItemMapper.selectByPrimaryKey(activityItemId);
            activityItem.setNum(activityItem.getNum()+1);
            activityItemMapper.updateByPrimaryKey(activityItem);
            model.addAttribute("cone", activityService.getContent(id));
            model.addAttribute("vote",activityService.get(id));
        }
        return "activity/result";
    }
}
